package net.valerijtimakov.homefinances.dao.storages.common.mysql.query_builders;

import java.util.HashMap;
import java.util.Map;

import net.valerijtimakov.homefinances.exceptions.AppExceptionWrongState;

public class UpdateQuery extends ConditionedQuery {
	
	private Map<String, Object> updatedFields = new HashMap<String, Object>();

	public void setFieldValue(String fieldName, Object fieldValue) {
		updatedFields.put(fieldName, fieldValue);
	}
	
	public UpdateQuery() {
		super();
	}

	public UpdateQuery(String tableName) {
		super(tableName);
	}
	
	@Override
	public String getSql() throws AppExceptionWrongState {
		StringBuilder whereLine = where.getWhereConditionLine();
		if (whereLine.length() == 0) {
			throw new AppExceptionWrongState("Неспецифичное обновление недопустимо!");
		}
		StringBuilder updFieldsLine = getFieldsUpdateLine();
		if (updFieldsLine.length() == 0) {
			return "";
		}
		return "UPDATE `" + tableName + "` SET " + updFieldsLine + whereLine + ";";
	}
	
	private StringBuilder getFieldsUpdateLine() {
		StringBuilder updFieldsLine = new StringBuilder();
		for (String fName : updatedFields.keySet()) {
			if (updFieldsLine.length() > 0) {
				updFieldsLine.append(",");
			}
			updFieldsLine.append("`");
			updFieldsLine.append(fName);
			updFieldsLine.append("`=");
			updFieldsLine.append(MySqlUtils.getValueLine(updatedFields.get(fName)));
		}
		return updFieldsLine;
	}

}
